package com.project.biz.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.framework.core.result.BasePage;
import com.project.biz.CmsCapitalFlowBiz;
import com.project.biz.CmsUserBalanceBiz;
import com.project.biz.UserBiz;
import com.project.common.exception.ServiceException;
import com.project.common.utils.IpageToPage;
import com.project.entity.CmsCapitalFlow;
import com.project.entity.CmsUser;
import com.project.mapper.CmsCapitalFlowMapper;
import com.project.pojo.dto.*;
import com.project.pojo.model.AddSystemUpperScoreModel;
import com.project.pojo.model.GetCmsCapitalFlowModel;
import com.project.pojo.model.UpdateDeductionModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Description: 资金流水业务层接口实现类
 * @Author: zhuchi
 * @CreateDate: 2020/11/18 22:38
 * @Version: 1.0
 */
@Slf4j
@Service
public class CmsCapitalFlowBizImpl extends ServiceImpl<CmsCapitalFlowMapper, CmsCapitalFlow> implements CmsCapitalFlowBiz {

    /**
     * 用户余额接口类
     */
    @Autowired
    private CmsUserBalanceBiz userBalanceBiz;

    /**
     * 用户业务层接口类
     */
    @Autowired
    private UserBiz userBiz;

    /**
     * 按条件分页查询资金流水
     * @param model
     * @return
     */
    public BasePage<CmsCapitalFlowDTO> getCapitalFlow(GetCmsCapitalFlowModel model){
        Page<CmsCapitalFlowDTO> page = new Page<>(model.getPageNo(), model.getPageSize());
        IPage<CmsCapitalFlowDTO> iPage = this.baseMapper.getCapitalFlow(page, model);
        BasePage<CmsCapitalFlowDTO> basePage = IpageToPage.toBasePage(iPage, CmsCapitalFlowDTO.class);

        return basePage;
    }

    /**
     * 按条件查询资金流水
     * @param model
     * @return
     */
    public List<CmsCapitalFlowDTO> getCapitalFlowList(GetCmsCapitalFlowModel model){
        List<CmsCapitalFlowDTO> list = this.baseMapper.getCapitalFlow(model);
        return list;
    }

    /**
     * 添加充值记录
     * @param addRechargeFlowDTO
     * @param userId 用户ID
     * @return
     */
    public int addRechargeFlow(AddRechargeFlowDTO addRechargeFlowDTO, Long userId){
        CmsCapitalFlow capitalFlow = new CmsCapitalFlow();
        BeanUtils.copyProperties(addRechargeFlowDTO, capitalFlow);
        capitalFlow.setBaseUserId(userId);
        capitalFlow.setHistoryType(1);//交易类型（1:充值,2:收益,3:消费）
        capitalFlow.setCreateUser(userId);
        capitalFlow.setCreateTime(new Date());
        capitalFlow.setStatus(1);
        return this.baseMapper.insert(capitalFlow);
    }

    /**
     * 添加收益记录
     * @param addIncomeFlowDTO
     * @param userId 用户ID
     * @return
     */
    public int addIncomeFlow(AddIncomeFlowDTO addIncomeFlowDTO, Long userId){
        CmsCapitalFlow capitalFlow = new CmsCapitalFlow();
        BeanUtils.copyProperties(addIncomeFlowDTO, capitalFlow);
        capitalFlow.setBaseUserId(userId);
        capitalFlow.setHistoryType(2);//交易类型（1:充值,2:收益,3:消费）
        capitalFlow.setCreateUser(userId);
        capitalFlow.setCreateTime(new Date());
        capitalFlow.setStatus(1);
        return this.baseMapper.insert(capitalFlow);
    }

    /**
     * 添加消费记录
     * @param addConsumeFlowDTO
     * @param userId 用户ID
     * @return
     */
    public int addConsumeFlow(AddConsumeFlowDTO addConsumeFlowDTO, Long userId){
        CmsCapitalFlow capitalFlow = new CmsCapitalFlow();
        BeanUtils.copyProperties(addConsumeFlowDTO, capitalFlow);
        capitalFlow.setBaseUserId(userId);
        capitalFlow.setHistoryType(3);//交易类型（1:充值,2:收益,3:消费）
        capitalFlow.setCreateUser(userId);
        capitalFlow.setCreateTime(new Date());
        capitalFlow.setStatus(1);
        return this.baseMapper.insert(capitalFlow);
    }

    /**
     * 系统上分
     * @param addSystemUpperScoreModel
     * @param userId
     * @return
     */
    public int addSystemUpperScore(AddSystemUpperScoreModel addSystemUpperScoreModel, Long userId){
        //被扣用户
        CmsUser addUser = this.userBiz.getById(addSystemUpperScoreModel.getBaseUserId());
        if (null == addUser){
            throw new ServiceException("请选择要上分的用户");
        }
        if (addSystemUpperScoreModel.getAmount().compareTo(new BigDecimal("0.00")) != 1){
            throw new ServiceException("请输入上分金额");
        }
        //获取用户钱包金额
        BigDecimal balance = this.userBalanceBiz.getUserBalance(addSystemUpperScoreModel.getBaseUserId());

        CmsCapitalFlow capitalFlow = new CmsCapitalFlow();
        capitalFlow.setBaseUserId(addSystemUpperScoreModel.getBaseUserId());
        capitalFlow.setHistoryType(1);//交易类型（1:充值,2:收益,3:消费）
        capitalFlow.setRechargeType(2);//充值类型（1:个人充值,2:系统上分）
        capitalFlow.setIncomeName("系统上分");
        capitalFlow.setUserAmount(balance);
        capitalFlow.setAmount(addSystemUpperScoreModel.getAmount());
        capitalFlow.setDescription(addSystemUpperScoreModel.getDescription());
        capitalFlow.setCreateUser(userId);
        capitalFlow.setCreateTime(new Date());
        capitalFlow.setStatus(1);
        int state = this.baseMapper.insert(capitalFlow);
        if (state > 0){
            //增加用户余额
            int addUserBalance = this.userBalanceBiz.updateAddUserBalance(addSystemUpperScoreModel.getBaseUserId(), addSystemUpperScoreModel.getAmount());
            log.info("系统给用户[{}]上分,用户当时余额:{}, 上分金额:{},执行状态：{}", addUser.getMobile(), balance, addSystemUpperScoreModel.getAmount(), addUserBalance);
        }

        return state;
    }

    /**
     * 系统扣款
     * @param updateDeductionModel
     * @param userId
     * @return
     */
    public int updateDeduction(UpdateDeductionModel updateDeductionModel, Long userId){
        //被扣用户
        CmsUser addUser = this.userBiz.getById(updateDeductionModel.getBaseUserId());
        if (null == addUser){
            throw new ServiceException("请选择扣款用户");
        }
        if (updateDeductionModel.getAmount().compareTo(new BigDecimal("0.00")) != 1){
            throw new ServiceException("请输入扣款金额");
        }
        //获取用户钱包金额
        BigDecimal balance = this.userBalanceBiz.getUserBalance(updateDeductionModel.getBaseUserId());
        if (balance.compareTo(updateDeductionModel.getAmount()) == -1){
            throw new ServiceException("用户余额不足,最多可扣除"+balance);
        }

        CmsCapitalFlow capitalFlow = new CmsCapitalFlow();
        capitalFlow.setBaseUserId(updateDeductionModel.getBaseUserId());
        capitalFlow.setHistoryType(3);//交易类型（1:充值,2:收益,3:消费）
        capitalFlow.setConsumeType(5);//消费类型（1:购买商品实付,2:购买商品抵扣,3:接单,4:实际金额大于预估金额补差价,5:系统扣款）
        capitalFlow.setIncomeName("系统扣款");
        capitalFlow.setUserAmount(balance);
        capitalFlow.setAmount(updateDeductionModel.getAmount());
        capitalFlow.setDescription(updateDeductionModel.getDescription());
        capitalFlow.setCreateUser(userId);
        capitalFlow.setCreateTime(new Date());
        capitalFlow.setStatus(1);
        int state = this.baseMapper.insert(capitalFlow);
        if (state > 0){
            //扣除用户余额
            int updateSubUserBalance = this.userBalanceBiz.updateSubUserBalance(updateDeductionModel.getBaseUserId(), updateDeductionModel.getAmount());
            log.info("系统扣除用户[{}]余额,用户当时余额:{}, 扣款金额:{},执行状态：{}", addUser.getMobile(), balance, updateDeductionModel.getAmount(), updateSubUserBalance);
        }

        return state;
    }

    /**
     * 后台统计
     * @return
     */
    public FundStatisticsDTO getFundStatistics(){
        return this.baseMapper.getFundStatistics();
    }

}
